/**
 * @Description : 注记交互
 * @Author : houhuawei
 * @Date : 2022-12-20 17:31:41
 * @param : {type}
 * @Returns :  
 * @Exception : 
 */

define([
    'map'
], function(map) {
    'use strict';
    let selection = {};
    let labelinfoHtml = '<div id="map_labelinfo"></div>';
    let _setting = {
        isinit: false,
        infoContainer_Id: "map_labelinfo",
        serverUrl: '',
        proj: '',
        idProp: '', // 要素的唯一键
        point_fontStyle: {
            "sheng": {
                textfont: 'bold 16px MicroSoft YaHei',
                textcolor: '#fff',
                outlinecolor: '#000',
                outlinewidth: 3
            },
            "shi": {
                textfont: 'bold 15px MicroSoft YaHei',
                textcolor: '#fff',
                outlinecolor: '#000',
                outlinewidth: 3
            },
            "xian": {
                textfont: 'bold 14px MicroSoft YaHei',
                textcolor: '#fff',
                outlinecolor: '#000',
                outlinewidth: 2
            },
            "xiang": {
                textfont: '13px MicroSoft YaHei',
                textcolor: '#fff',
                outlinecolor: '#000',
                outlinewidth: 1
            },
            "cun": {
                textfont: '12px MicroSoft YaHei',
                textcolor: '#fff',
                outlinecolor: '#000',
                outlinewidth: 1
            }
        },
        selected_point_fontStyle: {
            textfont: 'bold 16px MicroSoft YaHei',
            textcolor: '#fff',
            outlinecolor: '#f00',
            outlinewidth: 3
        },
        showField: [],
        styleFun: null, // function (feature, selected) {} 第一个参数为当前feature，第二个参数标记是否被选中，该函数应返回一个ol.style.Style的实例
        popHtml: null,
        beforeShowLayer: null,
        beforeHideLayer: null,
    }
    let vtLayer = null;
    let infoDom = null;
    let isUsing = true;
    let olmap = map.getMap();


    function init(params) {
        if (!_setting.isinit) {
            Object.assign(_setting, params, {
                isinit: true
            });
            $("body").append(labelinfoHtml);
            infoDom = $("#" + _setting.infoContainer_Id);
            _setting.idProp = _setting["idProp"] || 'pk_uid';
            // mvt图层
            vtLayer = new ol.layer.VectorTile({
                declutter: true,
                zIndex: 1000,
                visible: false,
                source: new ol.source.VectorTile({
                    format: new ol.format.MVT(),
                    projection: _setting["proj"] || 'EPSG:4490',
                    url: _setting["serverUrl"]
                }),
                style: styleFun
            });
            map.addLayer("labelmvt", vtLayer);
            bindEvent();
        }
    }

    let styleFun = function (feature, resolution) {
        let selected = !!selection[feature.get(_setting.idProp)];
        if(typeof _setting["styleFun"] === 'function'){
            return _setting["styleFun"](feature, selected);
        }
        let textfont = undefined;
        let textcolor = undefined;
        let outlinecolor = undefined;
        let outlinewidth = undefined;
        //点标注
        if (feature.properties_.layer.indexOf('_pt') != -1) {
            let type = feature.properties_.layer.substring(0, feature.properties_.layer.indexOf('_pt'));
            let labelfield = type + "_name";
            if (selected) {
                textfont = _setting.selected_point_fontStyle["textfont"];
                textcolor = _setting.selected_point_fontStyle["textcolor"];
                outlinecolor = _setting.selected_point_fontStyle["outlinecolor"];
                outlinewidth = _setting.selected_point_fontStyle["outlinewidth"];
            } else {
                textfont = _setting.point_fontStyle[type.toLowerCase()]["textfont"];
                textcolor = _setting.point_fontStyle[type.toLowerCase()]["textcolor"];
                outlinecolor = _setting.point_fontStyle[type.toLowerCase()]["outlinecolor"];
                outlinewidth = _setting.point_fontStyle[type.toLowerCase()]["outlinewidth"];
            }
            return new ol.style.Style({
                text: new ol.style.Text({
                    text: feature.properties_[labelfield],
                    font: textfont,
                    fill: new ol.style.Fill({
                        color: textcolor
                    }),
                    stroke: new ol.style.Stroke({
                        color: outlinecolor,
                        width: outlinewidth
                    })
                })
            });
        }
    }

    function getFeatureBypixel(pixel) {
        let features = olmap.getFeaturesAtPixel(pixel, {layerFilter: function (layer){
            return layer.get("c_layerId") === "labelmvt"
        }});
        return features ? features[0] : null;
    }

    function bindEvent() {
        olmap.on('singleclick', dealFeaInfo);
        olmap.on("pointermove", changeCursor);
    }

    function changeCursor(e) {
        if (isUsing) {
            let feature = getFeatureBypixel(e.pixel);
            let element = olmap.getTargetElement();
            if (feature) {
                element.style.cursor = 'pointer';
            } else {
                element.style.cursor = '';
            }
        }
    }

    function dealFeaInfo(event) {
        if (isUsing) {
            selection = {};
            vtLayer.setStyle(vtLayer.getStyle());
            let feature = getFeatureBypixel(event.pixel);
            if (!feature) {
                infoDom.hide();
                return;
            }
            selection[feature.get(_setting.idProp)] = feature;
            showFeaInfo(feature);
        }
    }

    function showFeaInfo(feature) {
        infoDom.text('');
        if (_setting.showField.length) {
            infoDom.append(getPopHtml(feature));
            infoDom.show();
        }
    }

    function getPopHtml(feature) {
        if (typeof _setting.popHtml === 'function') {
            return _setting.popHtml(feature);
        }
        let properties = feature.getProperties();
        let htmlDom = "";
        _setting.showField.forEach(field => {
            properties[field] && (htmlDom += "<div>" + field + "：" + properties[field] + "</div>");  
        })
        return htmlDom;
    }

    function setVisible(isshow) {
        if (isshow) {
            _setting.beforeShowLayer && _setting.beforeShowLayer();
            $("#map_labelinfo").show();
        }else{
            _setting.beforeHideLayer && _setting.beforeHideLayer();
            $("#map_labelinfo").hide();
        }
        vtLayer.setVisible(isshow);
        isUsing = isshow;
    }

    function destory() {
        olmap.un('singleclick', dealFeaInfo);
        map.removeLayer("labelmvt");
        _setting.isinit = false;
    }

    return{
        init: init,
        setVisible: setVisible,
        destory: destory
    }
});